package com.liu.android.gitee.app;

import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.widget.Toast;

import com.liu.android.gitee.ui.main.MainActivity;
import com.liu.android.gitee.utils.LogUtil;

import java.lang.Thread.UncaughtExceptionHandler;

/**
 * 未捕获异常处理类
 */
public class CrashHandler implements UncaughtExceptionHandler {
    private Application application;
    private UncaughtExceptionHandler mDefaultHandler;

    public static CrashHandler getInstance() {
        return CrashHandlerHolder.instance;
    }

    /**
     * 初始化,注册Context对象, 获取系统默认的UncaughtException处理器, 设置该CrashHandler为程序的默认处理器
     */
    public void init(Application application) {
        this.application = application;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                LogUtil.e("error ;", e);
                //LogUtil.e(this.getClass().toString(), e.toString());
            }
            // 重启app
            Intent intent = new Intent(application.getApplicationContext(), MainActivity.class);
            //PendingIntent restartIntent = PendingIntent.getActivity(application.getApplicationContext(), 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent restartIntent = PendingIntent.getActivity(application.getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            // 退出程序
            AlarmManager mgr = (AlarmManager) application.getSystemService(Context.ALARM_SERVICE);
            // 3秒后重启
            mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 3000, restartIntent);
            //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
            AppManager.getInstance().clear();
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    /**
     * 自己处理异常
     */
    private boolean handleException(Throwable ex) {
        if (null == ex) {
            return false;
        }
        //使用Toast来显示异信息
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(application.getApplicationContext(), "检测到程序异常，即将退出", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }.start();
        return true;
    }

    //单例模式-静态内部类
    private static class CrashHandlerHolder {
        private static final CrashHandler instance = new CrashHandler();
    }

}
